package com.tanhua.manage.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.tanhua.domain.db.UserFreeze;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.FreezeApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private FreezeApi freezeApi;
    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 远程调用dubbo服务，返回mybatis-plus的分页对象
        IPage<UserInfo> iPage = userInfoApi.findByPage(page, pagesize);
        // 构造返回给前端的分页数据
        PageResult pageResult =
                new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户基本资料
     */
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 接口名称：视频记录翻页
     */
    public ResponseEntity<Object> findVideoList(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult = videoApi.findByPage(page, pagesize, uid);
        List<Video> videoList = (List<Video>) pageResult.getItems();

        //2、创建返回的vo集合对象
        List<VideoVo> voList = new ArrayList<>();

        //3. 封装数据
        if (videoList != null) {
            for (Video video : videoList) {
                //3.1 创建vo对象，封装前端返回的数据
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(video, vo);
                //3.2 根据用户id查询用户并封装
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                //3.3 设置小视频封面
                vo.setCover(video.getPicUrl());
                //3.4 设置id、签名
                vo.setId(video.getId().toString());
                vo.setSignature(video.getText());
                vo.setHasLiked(0);

                //3.5 vo添加到集合
                voList.add(vo);
            }
        }
        //4. 设置到PageResult中
        pageResult.setItems(voList);

        //5. 响应
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> findMovementsList(
            Integer page, Integer pagesize, Long uid, Long state) {
        PageResult pageResult = publishApi.queryPublishList(page, pagesize, uid,state);
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        //3. 封装返回的结果MovementsVo集合
        //3.1 创建返回结果
        List<MovementsVo> voList = new ArrayList<>();
        //3.2 遍历查询的发布动态集合
        if (publishList != null) {
            for (Publish publish : publishList) {
                //3.2.1 创建vo对象
                MovementsVo vo = new MovementsVo();
                //3.2.2 封装数据：发布动态
                BeanUtils.copyProperties(publish, vo);
                //3.2.3 封装数据：先查询用户详情，再封装
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                    if (userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                //3.2.3 封装数据：其他参数
                vo.setId(publish.getId().toString());
                vo.setUserId(publish.getUserId());
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                vo.setDistance("50米");
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

                //3.2.4 对象添加到集合
                voList.add(vo);
            }
        }

        //4. 在把封装好的vo集合设置到分页对象中
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        Publish publish = publishApi.findById(publishId);

        //3.2.1 创建vo对象
        MovementsVo vo = new MovementsVo();
        //3.2.2 封装数据：发布动态
        BeanUtils.copyProperties(publish, vo);
        //3.2.3 封装数据：先查询用户详情，再封装
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        //3.2.3 封装数据：其他参数
        vo.setId(publish.getId().toString());
        vo.setUserId(publish.getUserId());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setDistance("50米");
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        //1. 根据动态id分页查询评论
        PageResult pageResult = commentApi.queryCommentsList(publishId,page,pagesize);

        //2. 获取查询数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        //3. 创建返回的vo集合数据
        List<CommentVo> voList = new ArrayList<>();

        //4. 封装voList
        if (commentList != null) {
            for (Comment comment : commentList) {
                CommentVo vo = new CommentVo();
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo,vo);
                }
                vo.setId(comment.getId().toString());

                vo.setContent(comment.getContent());
                vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                vo.setLikeCount(0);
                vo.setHasLiked(0);

                voList.add(vo);
            }
        }

        //5. 设置到分页对象中并返回
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户冻结操作
     * */
    public Integer freezeAccount(UserFreeze userFreeze) {

        Integer integer = freezeApi.save(userFreeze);





        return integer;
    }

    /**
     * 接口名称：解冻操作
     * */
    public Integer accountThaw(UserInfo userInfo) {
        Integer integer = userInfoApi.updates(userInfo);



        return integer;

    }

    /**
     * 删除冻结表中的冻结记录
     * @param userId
     */
    public void delectUnfreeze(Integer userId) {
        freezeApi.delectUnfreeze(userId);

    }



    //=================================================
    /**
     * 接口名称：动态通过
     * 接口路径：POST/manage/messages/pass·
     */
    public ResponseEntity<Object> statePass(String[] pubilshIdList) {
        Map<Object, Object> msg = new HashMap<>();
        try {
            //获取集合中的数据
            for (String id : pubilshIdList) {
                Publish publish = publishApi.findById(id);
                publishApi.updatePass(publish);
            }
            //返回数据
            msg.put("message","操作成功");
            String jsonString = JSON.toJSONString(msg);
            return ResponseEntity.ok(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
            msg.put("message","操作失败");
            String jsonString = JSON.toJSONString(msg);
            return ResponseEntity.ok(jsonString);
        }
    }
    //=================================================
    /**
     * 接口名称：动态拒绝
     * 接口路径：POST/manage/messages/reject
     */
    public ResponseEntity<Object> stateReject(String[] pubilshIdList) {
        Map<Object, Object> msg = new HashMap<>();
        try {
            //获取集合中的数据
            for (String id : pubilshIdList) {
                Publish publish = publishApi.findById(id);
                publishApi.updatereject(publish);
            }
            //返回数据
            msg.put("message","操作成功");
            String jsonString = JSON.toJSONString(msg);
            return ResponseEntity.ok(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
            msg.put("message","操作失败");
            String jsonString = JSON.toJSONString(msg);
            return ResponseEntity.ok(jsonString);
        }
    }
}
